package yxy.game.pm2.command.bandit;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.currency.CurrencyNotEnoughException;
import yxy.game.pm2.bean.task.TaskType;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.BanditMessage;
import yxy.game.pm2.module.bandit.Bandit;
import yxy.game.pm2.module.bandit.BanditModule;
import yxy.game.pm2.module.task.TaskHandle;

/** 剿匪 刷新任务 */
@MessageType(proto = Command.BanditUpdate, classtype = BanditMessage.BanditUpdateRequest.class)
public class CMD_BanditUpdate extends Command<BanditMessage.BanditUpdateRequest> {

	@Override
	public void execute(MessageSource messageSource, BanditMessage.BanditUpdateRequest request) {
		String playerCode = messageSource.getTag();

		BanditMessage.BanditUpdateResponse.Builder response = BanditMessage.BanditUpdateResponse.newBuilder();

		BanditModule banditModule = BanditModule.get(playerCode);
		try {
			if (banditModule.tryLock()) {
				{
					// 刷新操作
					try {
						banditModule.freshCost();
					} catch (CurrencyNotEnoughException e) {
						send(messageSource, response, new Result(Result.CostFail, e.getType().getNumber(), e.getDataId()));// 消费不足
						return;
					}

					banditModule.freshTask();
					banditModule.set();
					
					TaskHandle.handle(playerCode, TaskType.统计型_剿匪_刷新_次数, 1);
				}

				response.setRefreshfree(banditModule.freshFreeTimes());
				response.setRefreshtimes(Long.valueOf(banditModule.freshItem().getNumber()).intValue());
				for (Bandit bandit : banditModule.getTaskList()) {
					if (bandit.getDataId() <= 0) {
						continue;
					}
					BanditMessage.BanditTask.Builder task = BanditMessage.BanditTask.newBuilder();
					task.setId(bandit.getDataId());
					if (bandit.getEndTime() != null) {
						task.setTime(bandit.getEndTime().getMillis());
					} else {
						task.setTime(0);
					}
					response.addTasks(task);
				}

				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			banditModule.unlock();
		}
	}

	private void send(MessageSource messageSource, BanditMessage.BanditUpdateResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}